<?php
require_once 'Translator/Controller.php';

class BundleController extends Translator_Controller
{
	/**
	 * View a bundle.
	 */
	public function viewAction() {
		$code = $this->_getParam('code');
		$bundleid = intval($this->_getParam('bundle'));
		
		require_once 'models/LanguageModel.php';
		$languageModel = new LanguageModel();
		
		require_once 'models/BundleModel.php';
		$bundleModel = new BundleModel();
		
		$language = $languageModel->fetchLanguage($code);		
		$bundle = $bundleModel->fetchBundle($bundleid);
		
		if(empty($language) || empty($bundle)) {
			$this->_forward('error404', 'error');
			return;
		}
		
		if($language->original == 0) {
			$excludetranslated = ($this->_getParam('excludetranslated', 1) == 1 ? true : false);
			$keys = $bundleModel->fetchKeys($bundle->id, $language->id, $excludetranslated);
			
			$this->view->excludetranslated = $excludetranslated;
		} else {
			$keys = $bundleModel->fetchKeys($bundle->id);
		}
		
		// check if user can edit language
		$canedit = $this->user->canTranslate($language->id);
		
		$this->view->language = $language;
		$this->view->bundle = $bundle;
		$this->view->keys = $keys;
		$this->view->canedit = $canedit;
	}
	
	/**
	 * Manage bundles.
	 */
	public function manageAction() {
		$this->requireAdmin();
		
		require_once 'models/BundleModel.php';
		$bundleModel = new BundleModel();
		
		$this->view->bundles = $bundleModel->fetchBundles();
	}
	
	/**
	 * Create a new bundle.
	 */
	public function createAction() {
		$this->requireAdmin();
		
		require_once 'models/BundleModel.php';
		$bundleModel = new BundleModel();

		if($this->getRequest()->isPost()) {
			// validate form..
			$name = trim($this->getRequest()->getPost('name'));
			$alias = trim($this->getRequest()->getPost('alias'));
			$description = trim($this->getRequest()->getPost('description'));
			
			$errors = array();
			
			if(strlen($name) < 3) {
				$errors[] = 'Please provide a name with at least 3 chracters.';
			}
			
			if(strlen($alias) < 3 || preg_match('/$([a-z0-9-]+)^/i', $alias)) {
				$errors[] = 'Please provide an alias with at least 3 characters and using only latin letters, numbers and a dash (-).';
			}
			
			// file upload
			require_once 'Zend/File/Transfer.php';
			$upload = new Zend_File_Transfer();
			$upload->addValidator('Count', false, array('min' => 1, 'max' => 1));
			$upload->addValidator('Extension', false, array('properties'));
			$upload->addFilter('Rename', array(
					'target' => 'tmp/bundle-'.$this->user->id.'.properties', 
					'overwrite' => true)
			);

			if(!$upload->isValid('file')) {
				$errors[] = 'Please upload a properties file!';
			}
			
			else if (!$upload->receive()) {
				$errors[] = 'File upload failed.';
			}
			
			if(count($errors) == 0) {
				// save data for next step
				require_once 'Zend/Session/Namespace.php';
				$session = new Zend_Session_Namespace('translator');
				$session->bundle = array('name' => $name, 'alias' => $alias, 'description' => $description);
				
				$this->_helper->Redirector('create2', 'bundle');
			} else {
				$this->view->name = $name;
				$this->view->alias = $alias;
				$this->view->description = $description;
				
				$this->view->errors = $errors;
			}
		} else {
			$this->view->name = '';
			$this->view->alias = '';
			$this->view->description = '';
		}
	}
	
	/**
	 * Second step of the create material form.
	 */
	public function create2Action() {
		$this->requireAdmin();
		
		require_once 'models/BundleModel.php';
		$bundleModel = new BundleModel();
		
		require_once 'models/LanguageModel.php';
		$languageModel = new LanguageModel();
		
		require_once 'Zend/Session/Namespace.php';
		$session = new Zend_Session_Namespace('translator');
		
		if(!isset($session->bundle) || !file_exists('tmp/bundle-'.$this->user->id.'.properties')) {
			$this->_helper->Redirector('create', 'bundle');
		}
		
		$languages = $languageModel->fetchLanguages(false);
		$this->view->languages = $languages;
		
		// use data to store bundle
		if($this->getRequest()->isPost()) {
			$decisions = $this->getRequest()->getPost('decisions');
			
			// setup file upload object
			require_once 'Zend/File/Transfer.php';
			$upload = new Zend_File_Transfer();
			$upload->addValidator('Count', false, array('min' => 1, 'max' => 1));
			$upload->addValidator('Extension', false, array('properties'));
			
			// fetch data for each language
			foreach($languages as $language) {
				$language->usefile = false;
				
				// file upload
				if(isset($decisions[$language->code]) && $decisions[$language->code] == 'file') {
					$upload->addFilter('Rename', array(
							'target' => 'tmp/bundle-'.$this->user->id.'-'.$language->code.'.properties', 
							'overwrite' => true)
					);
		
					if($upload->isValid('file') && $upload->receive()) {
						$language->usefile = true;
					}
				}
			}
			
			// save bundle
			$bundleId = $bundleModel->insertBundle($session->bundle);
			
			// save original keys..
			require_once 'Translator/Properties.php';
			$properties = new Translator_Properties();
			
			$original = $properties->parse('tmp/bundle-'.$this->user->id.'.properties');
			$keyIds = $bundleModel->insertKeys($bundleId, $original);
			
			// work through translations needed for each language
			foreach($languages as $language) {
				// use file?
				if($language->usefile) {
					$translation = $properties->parse('tmp/bundle-'.$this->user->id.'-'.$language->code.'.properties');
				} 
				
				// mark all translations as unavailable
				else {
					$translation = array();
				}
					
				/* Combine results of translation file with the ones from the
				 * original file. Missing entries will be marked as untranslated. */ 
				$bundleModel->insertTranslation(
					$language->id, 
					$properties->combine($keyIds, $translation)
				);
			}
			
			// update statistics
			$bundleModel->createBundleStats($bundleId, $languages);
			
			// redirect to management page
			$this->_helper->FlashMessenger('Bundle created successfully.');
			$this->_helper->Redirector('manage', 'bundle');
		}
	}
	
	/**
	 * Toggle state of translation.
	 */
	public function togglestateAction() {
		$code = $this->_getParam('code');
		$id = intval($this->_getParam('id'));
		
		require_once 'models/LanguageModel.php';
		$languageModel = new LanguageModel();
		
		require_once 'models/BundleModel.php';
		$bundleModel = new BundleModel();
		
		$language = $languageModel->fetchLanguage($code);
		
		if(empty($language) || $language->original == 1 || $id <= 0) {
			die('error: no language / key');
		}
		
		if(!$this->user->canTranslate($language->id)) {
			die('error: no translator');
		}
		
		if($bundleModel->toggleKeyState($id, $language->id)) {
			die('translated');
		} else {
			die('untranslated');
		}
	}
}